<?php

namespace App\Models\Admin;
use App\Models\Orm\CooperativeCompany;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class AdminUser extends Authenticatable
{
    const PW_RESET_NO = 0;      // 未修改密码
    const PW_RESET_YES = 1;     // 已修改密码

    use Notifiable;
    protected $table='shayu_admin_users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    //用户角色
    public function roles()
    {
        return $this->belongsToMany(Role::class,'shayu_admin_role_user','user_id','role_id');
    }

    // 判断用户是否具有某个角色
    public function hasRole($role)
    {
        if (is_string($role)) {
            return $this->roles->contains('name', $role);
        }

        return !!$role->intersect($this->roles)->count();
    }

    // 判断用户是否具有某权限
    public function hasPermission($permission)
    {
        if (is_string($permission)) {
            $permission = Permission::where('name',$permission)->first();
            if (!$permission) return false;
        }

        return $this->hasRole($permission->roles);
    }

    // 给用户分配角色
    public function assignRole($role)
    {
        return $this->roles()->save($role);
    }

    //角色整体添加与修改
    public function giveRoleTo(array $RoleId){
        $this->roles()->detach();
        $roles=Role::whereIn('id',$RoleId)->get();
        foreach ($roles as $v){
            $this->assignRole($v);
        }
        return true;
    }

    /**
     * 判断用户是否root超管
     * @return bool
     */
    public function isRoot()
    {
        return $this->id == 1 ? true : false;
    }

    /**
     * 判断用户是否后台管理员
     * @return bool
     */
    public function isManager()
    {
        if (!$this->isRoot()) {
            $roles = $this->roles()->get();
            if ($roles) {
                foreach ($roles as $role) {
                    if ($role->id > 9999) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

    /**
     * 判断用户是否三方运营者
     * @return bool
     */
    public function isOperator()
    {
        if (!$this->isRoot() && !$this->isManager()) {
            $roles = $this->roles()->get();
            if ($roles) {
                foreach ($roles as $role) {
                    if ($role->id <= 9999) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

    /**
     * 获取关联合作方公司录入记录
     * @return mixed
     */
    public function getCooperativeCompany()
    {
        return $this->hasOne(CooperativeCompany::class, 'user_id', 'id')->getResults();
    }
}
